package top.broncho.anpods.util

import android.content.Context
import android.hardware.display.DisplayManager
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate


@CheckResult
@ExperimentalCoroutinesApi
fun Context.displayChange(): Flow<Int> = callbackFlow<Int> {
    val displayManager by lazy {
        getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
    }
    val displayListener = object : DisplayManager.DisplayListener {
        override fun onDisplayAdded(displayId: Int) = Unit
        override fun onDisplayRemoved(displayId: Int) = Unit
        override fun onDisplayChanged(displayId: Int) {
            safeOffer(displayId)
        }
    }
    displayManager.registerDisplayListener(displayListener, null)
    awaitClose { displayManager.unregisterDisplayListener(displayListener) }
}.conflate()